package com.waps;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

/**
 * 自定义的一个web view空间. 用于显示用户可以下载的应用程序，以赚取点数
 */
public class OffersWebView extends Activity
{
    private WebView webView = null;
    private String clickURL = null;

    private ProgressBar progressBar;
    private Dialog dialog = null;

    private String clientPackage = "";
    private String URL = AppConnect.SERVICE_URL + "account/offerlist?";	// offers页面的URL.
    private String urlParams = "";									    // URL 请求参数.
    private String userID = "";						     				// 推荐者ID.

    final String OFFERS = "Offers";

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {

        Bundle extras = getIntent().getExtras();
        initMetaData(extras);


        clickURL = URL + urlParams;

        clickURL = clickURL.replaceAll(" ", "%20");

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView( this.getResources().getIdentifier("offers_web_view", "layout", clientPackage));

        // 加载并显示WebView.
        webView = (WebView) findViewById(this.getResources().getIdentifier("offersWebView", "id", clientPackage));
        webView.setWebViewClient(new AppWebViewClient());

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        //创建一个旋转的进度条.
        progressBar = (ProgressBar)findViewById(getResources().getIdentifier("OfferProgressBar", "id", clientPackage));
        progressBar.setVisibility(View.VISIBLE);

        AppLog.i(OFFERS, "load web url: " + System.currentTimeMillis());
        webView.setDownloadListener(new DownloadListener(){
            public void onDownloadStart(String s, String s1, String s2, String s3, long l) {
                AppLog.i(OFFERS, s);
                AppLog.i(OFFERS, s1);
                AppLog.i(OFFERS, s2);
                AppLog.i(OFFERS, s3);
                AppLog.i(OFFERS, "========================");
            }
        });
        webView.loadUrl(clickURL);

//            todo:加入下载监听

//            new Thread(new WebDownloadListener(this)).start();


        AppLog.i(OFFERS, "Opening URL = [" + clickURL + "]");
    }

    class WebDownloadListener implements DownloadListener {

        public void onDownloadStart(String s, String s1, String s2, String s3, long l) {
            //To change body of implemented methods use File | Settings | File Templates.

        }
    }


    @Override
    protected void onResume()
    {

        super.onResume();

        // 获取新的焦点时刷新.
        if (clickURL != null && webView != null)
            webView.loadUrl(clickURL);
    }


    /**
     * 这个类处理所有自定义页面效果，比如打开一个连接或者判断是否电子市场的连接，呼出默认浏览器
     */
    private class AppWebViewClient extends WebViewClient
    {
        public void onPageFinished(WebView view, String url)
        {
            AppLog.i(OFFERS, "onPageFinished : " + System.currentTimeMillis());

            // 当页面加载完成时隐藏进度条.
            progressBar.setVisibility(View.GONE);
        }

        /**
         * 当用户点击URL时，此方法会在打开页面前被调用
         */
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
            AppLog.i(OFFERS, "URL = [" + url + "]");

            if (url.indexOf("market") > -1)
            {
                AppLog.i(OFFERS, "Market URL = [" + url + "]");

                try
                {
                    String str[] = url.split("id=");//“market://search?q=com.bayview.blackjack";
                    //					String composeedURL = "http://market.android.com/search?q=pname:"+str[1]+"&referrer="+clientPackage;
                    String composeedURL = "market://details?id="+str[1];
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(composeedURL));
                    startActivity(intent);
                    AppLog.i(OFFERS, "Open URL of application = [" + composeedURL + "]");
                }
                catch(Exception e)
                {

                    dialog = new AlertDialog.Builder(OffersWebView.this).setTitle("").setMessage("Android market is unavailable at this device. To view this link install market.").setPositiveButton("确定", new DialogInterface.OnClickListener()
                    {
                        public void onClick(DialogInterface dialog, int whichButton)
                        {
                            dialog.dismiss();
                        }
                    }).create();

                    try
                    {
                        dialog.show();
                    }
                    catch(Exception exp)
                    {
                        exp.printStackTrace();
                    }

                    AppLog.i(OFFERS, "Android market is unavailable at this device. To view this link install market.");
                }
            }
            else
                // 在webview保持重定向网址
                if (url.contains(AppConnect.BASE_REDIRECT_DOMAIN))
                {
                    AppLog.i(OFFERS, "Open redirecting URL = [" + url + "]");
                    view.loadUrl(url);
                }
                else
                // 打开一个新窗口.
                {
                    AppLog.i(OFFERS, "Opening URL in new browser = [" + url + "]");
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                }

            return true;
        }
    }

    /**
     * 处理Android 的返回键操作.
     */
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack())
        {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 构造绑定数据.
     * @param extras
     */
    private void initMetaData(Bundle extras)
    {
        if (extras != null)
        {
            urlParams = extras.getString(AppConnect.EXTRA_URL_PARAMS);
            clientPackage = extras.getString(AppConnect.EXTRA_CLIENT_PACKAGE);
            userID = extras.getString(AppConnect.EXTRA_USER_ID);

            // Generate the url parameters, then append the publisher ID.
            urlParams += "&publisher_user_id=" + userID;

            AppLog.i(OFFERS, "urlParams: [" + urlParams + "]");
            AppLog.i(OFFERS, "clientPackage: [" + clientPackage + "]");
        }
        else
        {
            AppLog.e(OFFERS, " offers meta data initialization fail.");
        }
    }
}
